import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import app.Usuario;

import database.UsuarioDAO;

/**
 * Servlet implementation class PublicarPropiedad
 */
public class Registrarse extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UsuarioDAO DBUser = null;
	private Connection con = null;
	private int errorCode = 0;
	
	public static int NOTVALIDMAIL = 1;
	public static int DISTINCTPASS = 2;
	public static int DBERROR = 3;
	public static int UNIQUEVIOLATION  = 4;
	public static int TOOMUCHCHARACTERS = 5;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Registrarse() {
        super();
    }
    
    public void init() throws ServletException {	
		super.init();

		try {
	        // Leyendo propiedades para la BD
	        Properties prop = new Properties();
	        ClassLoader loader = this.getClass().getClassLoader ();
	        InputStream in = loader.getResourceAsStream ("database/database.properties");
	        prop.load(in);
	        in.close();
	
	        String drivers = prop.getProperty("jdbc.drivers");
	        if (drivers != null)
	            System.setProperty("jdbc.drivers", drivers);
	
	        String url = prop.getProperty("jdbc.url");
	        String user = prop.getProperty("jdbc.user");
	        String password = prop.getProperty("jdbc.password");
	
	        // Creando conexion
	        con = DriverManager.getConnection(url, user, password);
	    } catch (IOException e1) {
	       e1.printStackTrace();
	    } catch (SQLException e2) {
	    	e2.printStackTrace();
	    }
	
	    try {
	    	DBUser = new UsuarioDAO(con);
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
    }
    
    private boolean hasProblems(HttpServletRequest request) {
    	// Comprueba datos correctos y borra los incorrectos
    	
    	String aux = request.getParameter("mail");
    	if ((aux == null) || (!aux.matches("(?ix)[a-z 0-9 _]+@[a-z 0-9]+.[a-z]{2, 3}"))) {
    		errorCode = NOTVALIDMAIL;
    		return true;
    	}
    	
    	String aux1 = request.getParameter("pass1");
    	aux = request.getParameter("pass2");
    	if (!aux.equals(aux1))  {
    		errorCode = DISTINCTPASS;
    		return true;
    	}
    	
    	return false;
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("register.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		
		PrintWriter out = response.getWriter();
		
		if (!hasProblems(request)) {
			Usuario u = new Usuario();
			String pass = request.getParameter("pass1");
			u.setCorreo(request.getParameter("mail"));
			u.setEdad(Integer.parseInt(request.getParameter("age")));
			u.setNombre(request.getParameter("name"));
			u.setTipo(Usuario.NORMAL);
			u.setUsuario(request.getParameter("nickname"));
			try {
				DBUser.insertar(u, pass);
			} catch (SQLException e) {
				switch (Integer.parseInt(e.getSQLState())) {
					case 8000:
						errorCode = DBERROR;
						break;
					case 23505:
						errorCode = UNIQUEVIOLATION;
						break;
					case 22001:
						errorCode = TOOMUCHCHARACTERS;
						break;
				} 
				response.sendRedirect("register.jsp?error=" + errorCode);
			}
			
		} else {
			// Reinsertar datos
			response.sendRedirect("register.jsp?error=" + errorCode);
		}
		
		out.println("" +
				"<head>" +
				"	<link rel=\"stylesheet\" type=\"text/css\" href=\"css/regStyle.css\">" +
				"	<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
	      		"	<title>Registrado con exito</title>" +
	      		"</head>" +
	      		"<body>" +
	      		"	<table class=\"mainTable\">" +
	            "		<tr>" +
	            "	   		<td>" +
	            "      			<a href=home.jsp><img width=\"100px\" height=\"50px\" src=\"img/logo.jpg\" /></a>" +
	            "   		</td>" +
	            "		</tr>" +
	            "		<tr> <td><hr color=\"#ffa200\" width=\"100%\" size=\"3px\"/></td> </tr>" +
	            "		<tr>" +
	            "			<th colspan=\"1\" class=\"centerButton\">" +
	            "				Se ha registrado con exito. Ya puede entrar a la pagina principal." +
	            "			</th> " +
				"   	</tr>" +
	            "		<tr>" +
	            "			<th colspan=\"1\" class=\"centerButton\"> " +
	            "           	<input type=\"button\" value=\"Aceptar\" onclick=\"window.location='index.jsp'\"/>" +
	            "			</th>" +
				"   	</tr>" +
				"	</table>" +
	      		"</body>"
		    );
		
	}
}
